package ym.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ym.mapper.CollectionMapper;
import ym.mapper.HouseMapper;
import ym.pojo.Collection;
import ym.pojo.House;
import ym.service.CollectionService;
import ym.vo.BaseResult;

import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class CollectionImpl implements CollectionService {
    @Autowired
    private CollectionMapper collectionMapper;
    @Autowired
    private HouseMapper houseMapper;

    @Override
    public BaseResult add(Integer userId, Integer houseId) {
        //先判断，是否收藏过
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId).eq("houseId", houseId);
        List<Collection> collections = collectionMapper.selectList(queryWrapper);
        if (collections.size() == 0) {
            Collection collection = new Collection();
            collection.setUserId(userId);
            collection.setHouseId(houseId);
            collectionMapper.insert(collection);
            return BaseResult.ok();
        } else {
            return new BaseResult(600, "您已经收藏过了", null);
        }


    }

    @Override
    public void delete(Integer userId, Integer houseId) {
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId).eq("houseId", houseId);
        collectionMapper.delete(queryWrapper);
    }

    @Override
    public List<House> findAllByUserId(Integer userId) {
        List<House> houseList = new ArrayList<>();
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        List<Collection> collectionList = collectionMapper.selectList(queryWrapper);
        for (Collection collection : collectionList) {
            House house = houseMapper.selectById(collection.getHouseId());
            houseList.add(house);
        }
        return houseList;
    }
}
